import axios from 'axios'
// import qs from 'qs'
import { getToken } from '@/utils/token'
import { ElMessage } from 'element-plus'

import host from '@/utils/ipConfig'
const service = axios.create({
  baseURL: host.ip,
  timeout: 6000
})
service.interceptors.request.use(
  config => {
    // 如果是get/delete请求 保证config的参数是params
    if (config.method.toLowerCase() === 'get' || config.method.toLowerCase() === 'delete') {
      config.params = config.data
      delete config.data
    }
    const token = getToken()
    if (token) {
      config.headers['token'] = token
    }
    // else if (config.method.toLowerCase() === 'post') {
    //   config.data = qs.stringify(config.data)
    // }
    return config
  },
  error => {
    ElMessage.error(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 0) {
      return res
    } else if (res.code === 500) {
      ElMessage.error('服务器异常')
    }
    // Promise.reject()
  },
  error => {
    return Promise.reject(error)
  }
)
export default service
